package com.example.bysj.Dao;
//201902104061徐中堂
import com.example.bysj.domain.StudentClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//声明数据库访问类
@Repository("studentClassDao")
public class StudentClassDao {
    //自动注入
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DepartmentDao departmentDao;
    //根据id查找班级
    public StudentClass getById(int id){
        String sql = "SELECT * FROM studentClass where id=?";
        List<StudentClass> studentClasses = jdbcTemplate.query(sql, new Object[]{id}, new RowMapper<StudentClass>() {
            @Override
            public StudentClass mapRow(ResultSet rs, int rowNum) throws SQLException {
                StudentClass studentClass = new StudentClass();
                studentClass.setId(rs.getInt("id"));
                studentClass.setDescription(rs.getString("description"));
                studentClass.setNo(rs.getString("no"));
                studentClass.setRemarks(rs.getString("remarks"));
                studentClass.setDepartment(departmentDao.find(rs.getInt("department_id")));
                return studentClass;
            }
        });
        if (!studentClasses.isEmpty()){
            return studentClasses.get(0);
        } else
            return null;
    }

    public boolean addStudentClass(StudentClass studentClass){
        String sql = "INSERT INTO student (id,description,no,remarks,department_id) VALUES(?,?,?,?,?)";
        int rowAffected = jdbcTemplate.update(sql,
                studentClass.getId(),
                studentClass.getNo(),
                studentClass.getRemarks(),
                studentClass.getDepartment().getId());
        if (rowAffected != 1){
            return false;
        } else {
            return true;
        }
    }
}
